<template>
  <ul class="navbar-nav">
    <li class="nav-item" v-for="(item, index) in sortedMenu" :key="item.Id" :class="{ active: activeMenuId == item.Id }">
        <router-link class="nav-link" :to="{ path: item.UrlRoute }">{{item.Name}} <span class="sr-only">(current)</span></router-link>
    </li>
</ul>
</template>

<script>
import lodash from 'lodash'
export default {
  name: 'TopMenu',
  props: {
    menus: {
      type: Array,
      required: true
    }
  },
  data () {
    return {
        sortedMenu: [],
        activeMenuId: 0
    }
  },
  watch: {
    $route: function () {
      this.updateMenu()
    }
  },
  mounted () {
      this.updateMenu()
  },
  methods: {
    updateMenu() {
      if(this.sortedMenu.length === 0)
        this.sortedMenu = lodash.sortBy(this.menus, ['DisplayOrder', 'Id']);
      const routes = this.$route.matched.concat()
      let matchRoute = lodash.find(routes, function(o) { return o.meta.mapurl && o.meta.mapurl !== ''; }),
          activeMenuItem = null;
      if(!lodash.isNil(matchRoute)) {
          activeMenuItem = lodash.find(this.sortedMenu, ['UrlRoute', matchRoute.meta.mapurl])
          if(!lodash.isNil(activeMenuItem)) this.activeMenuId = activeMenuItem.Id;
      } else {
        if(!lodash.isNil(this.$route.params.columnid)) { //List
          let cid = this.$route.params.columnid;
          if(typeof this.$route.params.columnid === 'string') cid = parseInt(this.$route.params.columnid);
          activeMenuItem = lodash.find(this.sortedMenu, ['Id', cid])
          if(!lodash.isNil(activeMenuItem)) this.activeMenuId = activeMenuItem.Id;
        }
      }
    },
  }
}
</script>
